package com.example.feidaolumanager.viewModel

import android.util.Log
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.idesign.cui.statefullayout.StatefulStatus
import com.example.feidaolu.modal.AreasItem
import com.example.feidaolumanager.Constants
import com.example.feidaolumanager.api.RetrofitClient
import com.example.feidaolumanager.pojo.Children
import com.example.feidaolumanager.pojo.ChildrenX
import com.example.feidaolumanager.pojo.MachineItem
import com.example.feidaolumanager.pojo.User
import kotlinx.coroutines.launch

class AreasViewModel : ViewModel() {

    val status: MutableLiveData<StatefulStatus> = MutableLiveData(StatefulStatus.Content)

    var tokenExpire = MutableLiveData(false)

    private var areas = mutableStateListOf<AreasItem>()

    var updatePageMachineArea = mutableStateOf("")

    var buildingSites = mutableStateListOf<ChildrenX>()

    var level1Areas = mutableStateListOf<AreasItem>()
    var level1AreasName = mutableStateListOf<String>()
    var level2Areas = mutableStateListOf<Children>()
    var level2AreasName = mutableStateListOf<MutableList<String>>()
    var level3Areas = mutableStateListOf<ChildrenX>()
    var level3AreasName = mutableStateListOf<MutableList<MutableList<String>>>()

    /**
     * 获取区域数据
     * @param user 用户对象
     * @param machine 可选参数，可以更具获取的数据生成该机器的type_name(类型名字)
     */
    fun getAreas(user: User, machine: MachineItem? = null) {

        viewModelScope.launch {
            val responseDTO = try {
                RetrofitClient.areasService.getAreas(ss_id = user.ss_id)
            } catch (e: Exception) {
                Log.e(this@AreasViewModel.toString(), "getAreas: ${e.message}")
                when (e) {
                    is java.io.InterruptedIOException -> {
                        status.value = StatefulStatus.NetError
                    }

                    else -> {}
                }
                return@launch
            }

            if (responseDTO.code != Constants.success_code) {
                if (responseDTO.msg == "401") {
                    // 登录过期，跳转到登录页
                    tokenExpire.value = true
                }
                return@launch
            }
            areas.addAll(responseDTO.data!!)
            level1Areas.clear()
            level2Areas.clear()
            level3Areas.clear()
            level1AreasName.clear()
            level2AreasName.clear()
            level3AreasName.clear()


            responseDTO.data!!.forEach { level1Area ->
                level1Areas.add(level1Area)
                level1AreasName.add(level1Area.title)

                // 创建数组装当前节点所有的子节点
                level2AreasName.add(arrayListOf())
                level3AreasName.add(arrayListOf())

                if (level1Area.children.isEmpty()) {
                    // 如果没有第二层，第二层和第三层也要补充一个空数组展位
                    level2AreasName.last().add("")
                    level3AreasName.last().add(arrayListOf(""))
                } else {
                    level1Area.children.forEach {
                        level2Areas.add(it)
                        // 放在循环外创建的最后一个节点的数组
                        level2AreasName.last().add(it.title)

                        level3AreasName.last().add(arrayListOf())

                        it.children.forEach {
                            level3AreasName.last().last().add(it.title)
                            level3Areas.add(it)
                        }
                    }
                }

            }


            if (machine != null) {
                getMachineAreaName(machine)
            }
        }
    }

    fun getAreas(user: User) {
        viewModelScope.launch {
            val responseDTO = try {
                RetrofitClient.areasService.getAreas(
                    userId = user.ss_id.toString(), userAccount = user.account,
                    level = user.level.toString()
                )
            } catch (e: Exception) {
                status.value = StatefulStatus.NetError
                return@launch
            }

            if (responseDTO.code == Constants.success_code) {
                buildingSites.clear()
                responseDTO.data?.let { buildingSites.addAll(it) }
            }
        }
    }

    private fun getMachineAreaName(machine: MachineItem): String {
        var result = ""



        Log.i("test", "getMachineAreaName: ${level1Areas.size}")

        result += (level1Areas.find {
            it.key == machine.area_one.toInt()
        }?.title + "/")

        result += level2Areas.find {
            it.key == machine.area_two.toInt()
        }?.title + "/"

        result += level3Areas.find {
            it.key == machine.area_three.toInt()
        }?.title ?: ""

        Log.i("test", "getMachineAreaName: $result")

        updatePageMachineArea.value = result
        return result
    }
}